package com.reshare.controller;

import com.reshare.base.BaseController;
import com.reshare.base.ResultInfo;
import com.reshare.bean.Seek;
import com.reshare.bean.User;
import com.reshare.mapper.UserMapper;
import com.reshare.query.SeekQuery;
import com.reshare.service.SeekService;
import com.reshare.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("seek")
public class SeekController extends BaseController {

    @Resource
    private SeekService seekService;

    @Autowired(required = false)
    private UserMapper userMapper;

    @RequestMapping("index")
    public String index() {
        return "seek/seek";
    }

    /**
     * 查询求购信息
     * @param query
     * @return
     */
    @RequestMapping("querySeek")
    @ResponseBody
    public Map<String,Object> querySeek(SeekQuery query){

        //查询求购信息
        Map<String, Object> map = seekService.querySeekByParams(query);
        return map;
    }


    @RequestMapping("add")
    public String add(Integer id,Model model) {
        if (id != null) {
            //查询用户信息
            Seek seek = seekService.selectByPrimaryKey(id);
            //存储数据
            model.addAttribute("seek",seek);
            return  "seek/edit";
        }
        return "seek/add";
    }

    /**
     * 添加求购信息
     * @param seek
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    public ResultInfo save(Seek seek, HttpServletRequest req) {
        //从cookie中获取userId
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(req);
        seek.setUserId(userId);
        seek.setUserName(userMapper.selectByPrimaryKey(userId).getUserName());
        //添加信息
        seekService.saveSeek(seek);
        //返回对象
        return success("添加成功！");
    }


    @RequestMapping("delete")
    @ResponseBody
    public ResultInfo delete(Integer seekId){
        seekService.deleteByPrimaryKey(seekId);
        return success("删除成功");
    }

}
